package edu.ccut.saturn.workflow.startWorkFlowModule.code;

import java.util.HashMap;
import java.util.List;

import edu.ccut.saturn.component.ComponentFactory;
import edu.ccut.saturn.component.DefaultComponent;
import edu.ccut.saturn.component.IParameterContext;
import edu.ccut.saturn.workflow.model.ActivityInfo;
import edu.ccut.saturn.workflow.model.LogicKeyInfo;
import edu.ccut.saturn.workflow.model.ParameterInfo;
import edu.ccut.saturn.workflow.model.WorkFlowInfo;

public class ExecuteExtLogic extends DefaultComponent {
	@SuppressWarnings("unchecked")
	@Override
	public void execute(IParameterContext parameterContext) throws Exception {
		WorkFlowInfo workFlowInfo = (WorkFlowInfo)parameterContext.getParameterValue(2);
		String process_instance_id =(String )parameterContext.getParameterValue(0);
		String activity_define_id =(String )parameterContext.getParameterValue(1);
		// 获得当前工作项对应活动的定义信息
		ActivityInfo activity = workFlowInfo.getActivityInfoById(activity_define_id);
		HashMap<String,String> customParamMap = (HashMap<String ,String>)parameterContext.getParameterValue(3);
		
		IParameterContext tempParameterContext = ComponentFactory
				.createParameterContext();
		String getFormDataKeyLogic = "edu.ccut.saturn.workflow::/parseWorkFlowModule/logic/GetFormDataValue.logic"; //$NON-NLS-1$
		// IComponent action =
		// ComponentManager.getInstance().getComponent(getFormDataKeyLogic);
		debug("sublogic has been started",parameterContext); //$NON-NLS-1$
		tempParameterContext.addParameter(process_instance_id, String.class);
		tempParameterContext.addParameter(null, HashMap.class);
		// action.execute(tempParameterContext);
		executeLogicSupportsTransaction(parameterContext, tempParameterContext,
				getFormDataKeyLogic);
		HashMap<String, String> formDataValueMap = (HashMap<String, String>) tempParameterContext
				.getParameterValue(1);
		// 如果有自定义logic需要执行，就先执行之

		List<LogicKeyInfo> logicList = activity.getLogicKey();
		if (logicList != null && logicList.size() > 0) {
			for (LogicKeyInfo logic : logicList) {
				tempParameterContext = ComponentFactory// 上下文不能重用
						.createParameterContext();
				// action =
				// ComponentManager.getInstance().getComponent(logic.getFullKey());
				debug("sublogic [" + logic.getFullKey() + "] has been started",parameterContext); //$NON-NLS-1$ //$NON-NLS-2$
				// 设置ｌｏｇｉｃ需要的上下文参数
				List<ParameterInfo> paramList = logic.getParamList();
				for (ParameterInfo paramInfo : paramList) {
					String value = (String) customParamMap.get(paramInfo.getKey());
					// 如果当前Map没有，就到数据库中查，
					if (value == null)
						value = (String) formDataValueMap.get(paramInfo
								.getKey());

					tempParameterContext.addParameter(value, String.class);
				}
				// action.execute(tempParameterContext);
				executeLogicSupportsTransaction(parameterContext,
						tempParameterContext, logic.getFullKey());
			}
		}
	}
}